import datetime
import os
import time
import pandas as pd
from flask import Blueprint, request, send_file

from utilsapp.mysql_con import db_connect, db_delete, db_pagelist, db_update, db_list
from utilsapp.mysql_con import (
    db_operation,
    db_fetchone,
    db_insert,
)
from utilsapp.common import parsing_permissions, get_url_user
from utilsapp.common import assign_value, parsing_data_id, find_str
from utilsapp import utils
import requests
import json

bluePrint = Blueprint("algorithm_warn", __name__)

# 以设备为单位展示告警
@bluePrint.route("/getlist", methods=["post"])
def device_list():
    a = request.json
    b = parsing_permissions(request)
    scope_id = assign_value(a, "scope_id", 0)
    scoped = parsing_data_id(scope_id, request)
    device_name = assign_value(a, "device_name")
    warn_level = assign_value(a, "warn_level")
    start_time = assign_value(a, "start_time")
    end_time = assign_value(a, "end_time")
    sql = f"""SELECT d.id as device_id ,d.device_name,max_warn_level,min_warn_level,warn_count,d.zone_id,
    d.factory_id,d.company_id,d.group_id,notice,start_time,end_time
    from device d
    LEFT JOIN (
    SELECT device_id,MIN(notice) as notice,count(id) as warn_count,MAX(warn_level) as max_warn_level,MIN(warn_level) as min_warn_level,
    MAX(pred_time) as end_time,MIN(create_time) as start_time
    FROM (SELECT w.* from algorithm_warn w INNER JOIN sensor s on s.id = w.sensor_id) a where is_show=1 GROUP BY device_id 
    ) as w on w.device_id = d.id"""
    query1 = "where 1=1"
    if scoped != "":
        query1 += f" and {scoped}"
    if device_name != "":
        query1 += f" and device_name like '%{device_name}%' "
    if warn_level != "" and warn_level != "0":
        query1 += f" and max_warn_level = {warn_level}"
    if start_time != "":
        query1 += f" and start_time > '{start_time}'"
    if end_time != "":
        query1 += f" and end_time < '{end_time}' "
    sql_ = f"select * from ({sql}) as a {query1} and warn_count != 0 order by notice asc,end_time desc"
    res = db_pagelist(sql_, a["page"])
    return res


# 查询设备下的告警
@bluePrint.route("/details/list", methods=["post"])
def details_list():
    try:
        a = request.json
        device_id = assign_value(a, "device_id")
        size = assign_value(a, "size", 999)
        page = assign_value(a, "page", 1)
        sql = f"""select m.*,w.*,s.sensor_name from algorithm_warn w
        LEFT JOIN algorithm_model m on m.m_m_code = w.m_m_code
        LEFT JOIN sensor s on w.sensor_id = s.id
        where w.is_show = 1 and w.device_id = {device_id} order by w.pred_time desc"""
        res = db_pagelist(sql, page, size)
        return res
    except Exception as e:

        return utils.fail(data=[], msg=str(e))
    
# 删除告警
@bluePrint.route("/delete")
def warn_delete():
    id = int(request.args.get("id"))
    sql = f"""update algorithm_warn set is_show = 0 where id = {id}"""
    res = db_operation(sql)
    affected_rows = res["Affected_rows"]
    if affected_rows >= 1:
        return {"code": 0, "msg": "删除成功", "data": res}
    else:
        return {"code": 1, "msg": "删除失败"}
    

